package com.laikan.reader.article.requester;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.FocusReplyDetailBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/8.
 */
public class FocusReplyDetailRequester {

    public static void getReplayList(final int mCurrentPage, String replyId, final TouchSwipeRefreshLayout refresher) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("reviewId", replyId);
        map.put("pageNo", mCurrentPage + "");
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                FocusReplyDetailBean result;
                Gson gson = new Gson();
                Type type = new TypeToken<FocusReplyDetailBean>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getFocusReplyData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            loadDataFailed("datafailed");
                        }else {
                            LaiKanEvent event = LaiKanEvent.getInstance();
                            event.setEventID(LaiKanEvent.EVENT_ID_GET_REPLY_LIST);
                            event.setElves(result);
                            LaikanApplication.postEvent(event);
                        }
                    }else {
                        loadDataFailed("datafailed");
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    loadDataFailed("datafailed");
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                loadDataFailed("netfailed");
                KLog.e("网络不给力，请重试。10");
            }

            @Override
            public void onFinish() {
                refresher.setRefreshing(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_bookfocus_replyList);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private static void loadDataFailed(String action) {
        LaiKanEvent event = LaiKanEvent.getInstance();
        event.setEventID(LaiKanEvent.EVENT_ID_COMMENT_NOTIC);
        event.setEventAction(action);
        LaikanApplication.postEvent(event);
    }

    //    /**
    //     * 获取回应接口数据
    //     */
    //    public static void loadMoreReplayDate(int mCurrentPage, String replyId, final TouchSwipeRefreshLayout refresher) {
    //        RequestListener requestListener = new RequestListener() {
    //            @Override
    //            public void onPreExecute() {
    //                KLog.e("---------volley onPreExecute!!!");
    //            }
    //
    //            @Override
    //            public void onSuccess(HttpResponse httpResponse) {
    //                BaseDataBean<BaseListDataBean<ReplyBean>> result;
    //                Gson gson = new Gson();
    //                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ReplyBean>>>() {
    //                }.getType();
    //                try {
    //                    result = gson.fromJson(httpResponse.responseContent, type);
    //
    //                    if (result != null) {
    //                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
    //                            ToastMgr.showShortToast(result.getError_msg());
    //                        }else {
    //                            LaiKanEvent event = LaiKanEvent.getInstance();
    //                            event.setEventID(LaiKanEvent.EVENT_ID_GET_MORE_REPLY);
    //                            event.setElves(result);
    //                            LaikanApplication.postEvent(event);
    //                        }
    //                        //                        ToastMgr.showShortToast(R.string.fw_data_loading_done);
    //                    }else {
    //                        showNotice(1);
    //                    }
    //                }catch (Exception e) {
    //                    showNotice(1);
    //                    e.printStackTrace();
    //                }
    //            }
    //
    //            @Override
    //            public void onError(VolleyErrorHandler errorHandler) {
    //                showNotice(2);
    //                KLog.e("网络不给力，请重试。11");
    //            }
    //
    //            @Override
    //            public void onFinish() {
    //                refresher.setLoading(false);
    //            }
    //        };
    //
    //        Requester requester = new Requester();
    //        requester.setUrl(APIProtocol.laikan_get_add_commentdetail + replyId + "/list?page=" + mCurrentPage);
    //        //        requester.setMapBody(map);
    //        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    //
    //        //        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.laikan_get_add_commentdetail + replyId + "/list?page=" + mCurrentPage, null, null, requestListener);
    //    }

    /**
     * @param type 为 1 数据加载失败
     * @param type 为 2 网络异常
     */
    private static String showContent;

/*    private static void showNotice(int type) {
        if (type == 1) {
            showContent = BasicApplication.getInstance().getString(R.string.laikan_data_load_failed);
        }else if (type == 2) {
            showContent = BasicApplication.getInstance().getString(R.string.laikan_network_anomaly);
        }
        LaiKanEvent event = LaiKanEvent.getInstance();
        event.setEventID(LaiKanEvent.EVENT_ID_SHOW_NOTICE);
        event.setEventAction(showContent);
        LaikanApplication.postEvent(event);
    }*/

    /**
     * 发送评论回复
     *
     * @param comment
     * @param replyId
     * @param mloadingDialog
     */
    public static void sendReply(String comment, final String replyId, final LoadingDialog mloadingDialog) {
        if (comment.length() == 0) {
            ToastMgr.showShortToast(R.string.laikan_empty_content_toast);
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("objectId", replyId);
        map.put("content", comment);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                mloadingDialog.show();
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("FocusReplyDetail : " + httpResponse.responseContent);
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        SPUtil.putBoolean("refresh_article_comment", true);
                        ToastMgr.showShortToast(R.string.comment_success);
                        LaiKanEvent event = LaiKanEvent.getInstance();
                        event.setEventID(LaiKanEvent.EVENT_ID_ARTICLE_SEND_REPLY);
                        Map<String, Object> map = new HashMap<>();
                        map.put("replyId", replyId);
                        LaikanApplication.postEvent(event.setEventMap(map));
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。12");
            }

            @Override
            public void onFinish() {
                mloadingDialog.dismiss();
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_bookfocus_addreply);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
        //        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_get_add_commentdetail + replyId + "/add?", map, null, null, requestListener);
    }

    public static void clickToSupport(final View view, final String mArticleId, int type, final int eventId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("objectId", mArticleId);
        map.put("type", type + "");
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    refredhLikeCount(null, false, eventId);
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(httpResponse.responseContent);
                    if (null == jsonObject || Integer.parseInt(Constants.RESULT_OK) != jsonObject.getInt("result")) {
                        ToastMgr.showLongToast(jsonObject.getString("error_msg"));
                        refredhLikeCount(null, false, eventId);
                    }else {
                        SPUtil.putBoolean("refresh_article_comment", true);
                        JSONObject jsonObjectData = jsonObject.getJSONObject("data");
                        boolean wasFavor = jsonObjectData.getBoolean("wasFavor");
                        int favorCount = jsonObjectData.getInt("favorCount");
                        ImageView clickToSupport = (ImageView)((RelativeLayout)view).findViewById(R.id.iv_clicktosupport);
                        TextView likeCount = (TextView)((RelativeLayout)view).findViewById(R.id.tv_clicktosupport);
                        if (favorCount > 99) {
                            likeCount.setText(R.string.tv_comment_more);
                        }else {
                            likeCount.setText(favorCount + "");
                        }
                        if (wasFavor) {
                            clickToSupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable
                                .iv_click_to_support), Color
                                .parseColor("#66ccdd"))));
                        }else {
                            clickToSupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable.iv_click_to_support), Color.parseColor("#999999"))));
                        }
                        refredhLikeCount(favorCount + "", wasFavor, eventId);
                        scaleAnimation(clickToSupport);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    refredhLikeCount(null, false, eventId);
                }
                KLog.e("click json " + httpResponse.responseContent);

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showLongToast(R.string.fw_return_data_error);
                refredhLikeCount(null, false, eventId);
            }

            @Override
            public void onFinish() {
            }

            public void refredhLikeCount(String totalLikeCount, boolean isFavor, int eventId) {
                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(eventId);
                Map<String, Object> mapEvent = new HashMap<>();
                mapEvent.put("totallikecount", totalLikeCount);
                mapEvent.put("replyId", mArticleId);
                mapEvent.put("isFavor", isFavor);
                BasicApplication.postEvent(event.setEventMap(mapEvent));
            }

            private void scaleAnimation(View view) {
                //初始化
                Animation scaleAnimation = new ScaleAnimation(0.1f, 1.0f, 0.1f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                //设置动画时间
                scaleAnimation.setDuration(500);
                scaleAnimation.setFillAfter(false);
                view.startAnimation(scaleAnimation);
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_focus_update_praise);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

}
